﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Easily
{
    public partial class frmIIC : Form
    {
        private GeneralIcon MyIcon = null;  //保存传入的控件对象
        /// <summary>
        ///构造函数
        ///主要功能：加载保存的控件设置；生成初始代码；
        /// </summary>
        public frmIIC(GeneralIcon icon)
        {
            InitializeComponent();
            this.MyIcon = icon;
            //添加头文件
            this.MyIcon.code.HeadFile = "#include \"i2c.h\"";
            //添加可供选择的系统变量到cBox_var中
            if (Globaldefine.FrmParent.ActivedrmGraphicFlow != null)
            {
                //全局变量
                for (int i = 0; i < Globaldefine.FrmParent.ActivedrmGraphicFlow.m_VariableSys.Count; i++)
                {
                    cBox_revar.Items.Add(Globaldefine.FrmParent.ActivedrmGraphicFlow.m_VariableSys[i]);
                    cBox_sendvar.Items.Add(Globaldefine.FrmParent.ActivedrmGraphicFlow.m_VariableSys[i]);
                }
                //传感器局部变量
                foreach (var item in Globaldefine.FrmParent.ActivedrmGraphicFlow.m_Sensor_VariableLocal.Values)
                {
                    this.cBox_revar.Items.Add(item);
                    this.cBox_sendvar.Items.Add(item);
                }
                //局部变量
                foreach (var item in Globaldefine.FrmParent.ActivedrmGraphicFlow.m_VariableLocal)
                {
                    this.cBox_revar.Items.Add(item);
                    this.cBox_sendvar.Items.Add(item);
                }
            }
            //默认选中列表的第1个数据
            //模块号
            if (cBox_iic.Items.Count > 0)
                cBox_iic.SelectedIndex = 0;
            //主从机选择
            if (cBox_mode.Items.Count > 0)
                cBox_mode.SelectedIndex = 0;
            //波特率
            if (cBox_baud.Items.Count > 0)
                cBox_baud.SelectedIndex = 0;
            //初始化地址(默认123)
            if (txtBox_initAddress.Text.ToString() == "")
                txtBox_initAddress.Text = "123";
            //载入保存的参数
            if (MyIcon.code.Save != "")
            {
                //保存的参数共有4项，以英文分号';'分开
                //保存的内容分别是：（1）iic模块号：IIC_0,IIC_1;
                //（2）主从机选择：主机/从机（3）初始化地址；
                //（4）波特率选择；（5）是否读取数据true/false；
                //（6）读取数据从机地址；（7）读取数据命令；
                //（8）存放读取数据的变量；（9）是否写入数据true/false；
                //（10）写入数据的从机地址；（11）存放写入数据的变量
                string[] tmp = MyIcon.code.Save.Split(';');
                //i2c模块号
                if (tmp[0] == "IIC_0")
                {
                    cBox_iic.SelectedIndex = 0;
                }
                else if (tmp[0] == "IIC_1")
                {
                    cBox_iic.SelectedIndex = 1;
                }
                //主从机选择
                if (tmp[1] == "主机")
                {
                    cBox_mode.SelectedIndex = 0;
                }
                else if (tmp[1] == "从机")
                {
                    cBox_mode.SelectedIndex = 1;
                }
                //初始化地址
                txtBox_initAddress.Text = tmp[2];
                //波特率
                cBox_baud.SelectedItem = tmp[3];
                if (tmp[4]=="true")
                {
                    rBtn_read.Checked = true;
                    //读取数据从机地址
                    txtBox_slaveAddress_read.Text = tmp[5];
                    //读取数据命令
                    txtBox_cmd.Text = tmp[6];
                    
                }
                if (tmp[8]=="true")
                {
                    rBtn_write.Checked = true;
                    //写入数据从机地址
                    txtBox_slaveAddress_write.Text = tmp[9];
                }
               
                //发送变量
                if (!cBox_revar.Items.Contains(tmp[7]))  //防止item尚未被添加
                    cBox_revar.Items.Add(tmp[7]);
                if (!cBox_sendvar.Items.Contains(tmp[10]))  //防止item尚未被添加
                    cBox_sendvar.Items.Add(tmp[10]);
                cBox_revar.SelectedItem = tmp[7];
                cBox_sendvar.SelectedItem = tmp[10];
            }
            btn_confirm_Click(new object(), new EventArgs());//触发确认

        }

        /// <summary>
        /// 点击“确定”按钮
        /// 主要功能：根据配置生成新代码，并设置对话返回为OK
        /// </summary>
        private void btn_confirm_Click(object sender, EventArgs e)
        {
            MyIcon.code.Save = "";
            string modeSelect = "";
            if (cBox_mode.SelectedItem.ToString() == "主机")
            {
                modeSelect = "0";
            }
            else if (cBox_mode.SelectedItem.ToString() == "从机")
            {
                modeSelect = "1";
            }
            //初始化代码
            MyIcon.code.Initialization = "i2c_init(" + cBox_iic.SelectedItem.ToString()
                + "," + modeSelect + ","+txtBox_initAddress.Text.ToString() +","+
                cBox_baud.SelectedItem.ToString()  + ");//初始化iic模块";
            //通过IIC读取数据           
            if (rBtn_read.Checked == true)
            {
                #region IIC读取操作
                if (cBox_revar.SelectedItem != null && cBox_revar.SelectedItem.ToString() != "")
                {
                    string vari = cBox_revar.SelectedItem.ToString();
                    //如果读取一个字节变量
                    //函数原型uint8_t i2c_read1(uint8_t I2C_No,uint8_t slaveAddress,uint8_t commond,uint8_t *Data);
                    if (vari[0] != 'g')
                        MyIcon.code.InsertCode = "i2c_read1(" + cBox_iic.SelectedItem.ToString() + ","
                            + txtBox_slaveAddress_read.Text.ToString() + ","
                            + txtBox_cmd.Text.ToString() +","+ vari + ");  //读取数据\r\n";
                    else
                    {
                        string length = "";
                        int index = 0;
                        //获取数组长度
                        for (index = 1; index < vari.Length; index++)
                        {
                            if (!Char.IsDigit(vari, index))
                                break;
                        }
                        length = vari.Substring(1, index - 1);
                        //函数原型uint8_t i2c_readN(uint8_t I2C_No,uint8_t slaveAddress,uint8_t commond,uint8_t *Data, uint8_t DataNum);                                  
                        MyIcon.code.InsertCode = "i2c_readN(" + cBox_iic.SelectedItem.ToString() + ","
                            + txtBox_slaveAddress_read.Text.ToString() + "," + txtBox_cmd.Text.ToString() + ","
                            + vari +","+ length + ");//发送数据\r\n";
                    }
                }
                string tempRevar = "";
                string tempCmd = "";
                string tempAddress_read = "";
                if (cBox_revar.SelectedItem != null)
                    tempRevar = cBox_revar.SelectedItem.ToString();
                if (txtBox_cmd.Text != null)
                    tempCmd = txtBox_cmd.Text.ToString();
                if (txtBox_slaveAddress_read.Text != null)
                    tempAddress_read = txtBox_slaveAddress_read.Text.ToString();
                MyIcon.code.Comment = "通过IIC" + cBox_iic.SelectedItem.ToString() + "发送数据："
                    + tempRevar;
                //保存代码
                MyIcon.code.Save = cBox_iic.SelectedItem.ToString() + ";" + cBox_mode.SelectedItem.ToString() + ";"
                + txtBox_initAddress.Text.ToString()+";" + cBox_baud.SelectedItem.ToString() + ";"+"true"+";" + tempAddress_read + ";"
                + tempCmd + ";" + tempRevar;
                #endregion

                #region 既进行读取又进行写入操作
                //如果进行了写入操作
                if (rBtn_write.Checked == true)
                {
                    if (cBox_sendvar.SelectedItem != null && cBox_sendvar.SelectedItem.ToString() != "")
                    {
                        string vari = cBox_sendvar.SelectedItem.ToString();
                        //如果写入一个字节
                        //函数原型i2c_write1(uint8_t I2C_No, uint8_t slaveAddress, uint8_t Data);
                        if (vari[0] != 'g')
                            MyIcon.code.InsertCode += "i2c_write1(" + cBox_iic.SelectedItem.ToString() + ","
                                + txtBox_slaveAddress_write.Text.ToString() + vari + ");  //写入数据\r\n";
                        //如果写入多个字节  
                        else
                        {
                            string length = "";
                            int index = 0;
                            //获取数组长度
                            for (index = 1; index < vari.Length; index++)
                            {
                                if (!Char.IsDigit(vari, index))
                                    break;
                            }
                            length = vari.Substring(1, index - 1);
                            //函数原型i2c_writeN(uint8_t I2C_No, uint8_t slaveAddress, uint8_t *Data, uint8_t DataNum);                                  
                            MyIcon.code.InsertCode += "i2c_writeN(" + cBox_iic.SelectedItem.ToString() + ","
                                + txtBox_slaveAddress_read.Text.ToString() + "," + vari + "," + length + ");//发送数据\r\n";
                        }
                    }
                    string tempSendvar = "";
                    string tempAddress_write = "";
                    if (cBox_sendvar.SelectedItem != null)
                        tempSendvar = cBox_sendvar.SelectedItem.ToString();
                    if (txtBox_slaveAddress_write.Text != null)
                        tempAddress_write = txtBox_slaveAddress_write.Text.ToString();
                    MyIcon.code.Comment = "通过IIC" + cBox_iic.SelectedItem.ToString() + "发送数据："
                        + tempSendvar;
                    //保存代码
                    MyIcon.code.Save += ";"+"true"+";" + tempAddress_write + ";" + tempSendvar;
                }
                #endregion

                #region 只进行读取操作，未进行写入
                else
                {
                    MyIcon.code.Save += ";" + "false" + ";" + "" + ";" + "";
                }
                #endregion
            }
            //未通过IIC读取数据 
            else
            {
                #region 未进行写入和读取操作
                //未进行写入和读取操作,后面的5个属性记为空
                if (rBtn_write.Checked == false)
                {
                    MyIcon.code.Save = cBox_iic.SelectedItem.ToString() + ";" + cBox_mode.SelectedItem.ToString() + ";"
                    + txtBox_initAddress.Text.ToString() + ";" + cBox_baud.SelectedItem.ToString() + ";" + "false" + ";" + "" + ";"
                    + "" + ";" + "" + ";" + "false" + ";" + "" + ";" + "";
                } 
                #endregion

                #region 如果未进行读取操作只进行了写入操作
                else if (rBtn_write.Checked == true)
                {
                    if (cBox_sendvar.SelectedItem != null && cBox_sendvar.SelectedItem.ToString() != "")
                    {
                        string vari = cBox_sendvar.SelectedItem.ToString();
                        //如果写入一个字节
                        //函数原型i2c_write1(uint8_t I2C_No, uint8_t slaveAddress, uint8_t Data);
                        if (vari[0] != 'g')
                            MyIcon.code.InsertCode += "i2c_write1(" + cBox_iic.SelectedItem.ToString() + ","
                                + txtBox_slaveAddress_write.Text.ToString() + vari + ");  //写入数据\r\n";
                        //如果写入多个字节  
                        else
                        {
                            string length = "";
                            int index = 0;
                            //获取数组长度
                            for (index = 1; index < vari.Length; index++)
                            {
                                if (!Char.IsDigit(vari, index))
                                    break;
                            }
                            length = vari.Substring(1, index - 1);
                            //函数原型i2c_writeN(uint8_t I2C_No, uint8_t slaveAddress, uint8_t *Data, uint8_t DataNum);                                  
                            MyIcon.code.InsertCode += "i2c_writeN(" + cBox_iic.SelectedItem.ToString() + ","
                                + txtBox_slaveAddress_read.Text.ToString() + "," + vari + "," + length + ");//写入数据\r\n";
                        }
                    }
                    string tempSendvar = "";
                    string tempAddress_write = "";
                    if (cBox_sendvar.SelectedItem != null)
                        tempSendvar = cBox_sendvar.SelectedItem.ToString();
                    if (txtBox_slaveAddress_write.Text != null)
                        tempAddress_write = txtBox_slaveAddress_write.Text.ToString();
                    MyIcon.code.Comment = "通过IIC" + cBox_iic.SelectedItem.ToString() + "写入数据："
                        + tempSendvar;
                    //保存代码
                    MyIcon.code.Save = cBox_iic.SelectedItem.ToString() + ";" + cBox_mode.SelectedItem.ToString() + ";"
                    + txtBox_initAddress.Text.ToString() + cBox_baud.SelectedItem.ToString() + ";" + "false" + ";" + "" + ";"
                    + "" + ";" + "" + ";" + tempAddress_write + ";" + tempSendvar;
                } 
                #endregion
            }
            this.DialogResult = DialogResult.OK;
        }

        /// <summary>
        /// 单击“取消”按钮
        /// 主要功能：设置返回结果为取消
        /// </summary>
        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }
        
        /// <summary>
        /// 点击“注释说明”按钮
        /// 功能概要：为控件添加自定义注释说明
        /// </summary>
        private void btn_comment_Click(object sender, EventArgs e)
        {
            using (frmNodeEditer NE = new frmNodeEditer(this.MyIcon.code.Comment))
            {
                if (NE.ShowDialog() == DialogResult.OK)
                    this.MyIcon.code.Comment = NE.NoteEdit;
            }
        }
    }
}
